package com.gec.system.controller;

import com.aliyuncs.utils.StringUtils;
import com.baomidou.mybatisplus.extension.api.R;
import com.gec.system.service.MsmService;
//import com.gec.system.util.RandomUtil;
import com.gec.system.util.RandomUtils;
import com.gec.system.util.Result;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "短信业务")
@RequestMapping("/admin/system/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/send/{phone}")
    public Result sendMsm(@PathVariable String phone) {

        //1 从redis获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code)) {
            return Result.ok();
        }

        //生成一个随机值
        code = RandomUtils.getFourBitRandom();
        Map<String,Object> param  = new HashMap<>();
        param.put("code",code);

        //调用service发送短信的方法
        boolean isSend = msmService.send(param,phone);

        if(isSend) {
            //发送成功,把发送成功验证码放到redis里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone,code,2, TimeUnit.MINUTES);
            System.out.println(phone+"存了"+code);

            return Result.ok();
        } else {
            return Result.fail().message("短信发送失败");
        }

    }


    public boolean confirm(String phone, String smsCode) {

       return  this.redisTemplate.opsForValue().get(phone).equals(smsCode);
    }
}
